package org.pjug.linuxadvices.servlets;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.Logger;

import org.pjug.linuxadvices.database.*;
/**
 * Przykladowy servlet.
 * @author Tomasz Trela
 */
public class SampleServlet extends HttpServlet {

		protected final Logger logger = Logger.getLogger(SampleServlet.class);
		private DBConnection dbConnection = null;

		/**
		*	Inicjalizacja servletu.
		*	
		*/
		public void init() throws UnavailableException {
			dbConnection = (DBConnection)getServletContext().getAttribute("dbConnection");
        if ( dbConnection == null) {
					throw new UnavailableException("Could not get database connection.");
				}
		}
   
    /** 
    * Procesing zadania. 
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Przykladowy servlet.</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>ContexPath servletu: " + request.getContextPath () + "</h1>");
						out.println("<br />");
						out.println("<h2>Servlet zostal poprawnie zainicjowany, dbConnection= " + dbConnection.toString() +"</h2>");
						out.println("<br />");
						out.println("<br />");
            out.println("</body>");
            out.println("</html>");
        } finally { 
            out.close();
        }
    } 

    /** 
    * Obsluga zadania <code>GET</code>.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Obsulga zadania <code>POST</code>.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Krotki opis servletu. 
    */
    public String getServletInfo() {
        return "Przykladowy servlet.";
    }
}
